package planilha.menu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;

import planilha.Planilha;
import planilha.model.MovimentacoesTableModel;

public class PlanilhaMenuBar extends PlanilhaMenuBarUI {

	private static final long serialVersionUID = 4360420531421943048L;

	public PlanilhaMenuBar(final MovimentacoesTableModel movimentosModel,//
			final Planilha planilha) {
		novo.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					JFileChooser chooser = new JFileChooser();
					chooser.setFileFilter(new FileFilter() {
						@Override
						public String getDescription() {
							return "*.xml";
						}

						@Override
						public boolean accept(File f) {
							return f.getName().endsWith(".xml")//
									|| f.isDirectory();
						}
					});
					int op = chooser.showSaveDialog(PlanilhaMenuBar.this
							.getParent());
					if (op == JFileChooser.APPROVE_OPTION) {
						File f = chooser.getSelectedFile();
						if (!f.getName().endsWith(".xml"))
							f.renameTo(f = new File(f.getParentFile(),//
									f.getName() + ".xml"));
						if (!f.exists())
							f.createNewFile();
						movimentosModel.open(f);
						planilha.updateRodape();
						planilha.updateFiltro();
					}
				} catch (Exception e1) {
					trataException(e1);
				}
			}
		});
		abrir.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				try {
					JFileChooser chooser = new JFileChooser();
					chooser.setFileFilter(new FileFilter() {
						@Override
						public String getDescription() {
							return "*.xml";
						}

						@Override
						public boolean accept(File f) {
							return f.getName().endsWith(".xml")
									|| f.isDirectory();
						}
					});
					int op = chooser.showOpenDialog(PlanilhaMenuBar.this
							.getParent());

					if (op == JFileChooser.APPROVE_OPTION) {
						File f = chooser.getSelectedFile();
						movimentosModel.open(f);
						planilha.updateRodape();
						planilha.updateFiltro();
					}
				} catch (Exception e1) {
					trataException(e1);
				}
			}
		});
	}

	private void trataException(Exception e1) {
		String msg = e1.getMessage();
		JOptionPane.showMessageDialog(this, msg);
		e1.printStackTrace();
	}
}
